package com.dangf.app.launcher.activity

import android.content.Intent
import android.support.v7.app.AlertDialog
import android.support.v7.widget.GridLayoutManager
import android.view.KeyEvent
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.dangf.app.launcher.R
import com.dangf.app.launcher.adapter.MainAppListAdapter
import com.dangf.app.launcher.app.BaseActivity
import com.dangf.app.launcher.app.V
import com.dangf.app.launcher.entity.Soft
import com.dangf.app.launcher.entity.event.IOEType
import com.dangf.app.launcher.entity.event.IOEvent
import com.dangf.app.launcher.entity.event.MainEType
import com.dangf.app.launcher.entity.event.MainEvent
import com.dangf.app.launcher.service.EventService
import com.dangf.app.launcher.service.SockectService
import com.dangf.app.launcher.utils.AnimUtil
import com.dangf.app.launcher.utils.caleader.CalendarUtil
import com.haozhang.lib.SlantedTextView
import com.white.progressview.CircleProgressView
import com.yanzhenjie.nohttp.Headers
import com.yanzhenjie.nohttp.NoHttp
import com.yanzhenjie.nohttp.download.DownloadListener
import kotlinx.android.synthetic.main.activity_main.*
import pw.hais.utils_lib.utils.AppUtils
import pw.hais.utils_lib.utils.DateUtils
import java.util.*


class MainActivity : BaseActivity(R.layout.activity_main), BaseQuickAdapter.OnItemClickListener, View.OnClickListener {
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.text_mobile_name -> {  //进入关于界面
                startActivity(Intent(context, AdminActivity::class.java))
            }
            R.id.text_ad -> {  //进入广告页面
                startActivity(Intent(context, AdvertActivity::class.java))
            }
            R.id.text_now_time -> {  //进入天气界面
                if (AppUtils.isInstallApp("hanjie.app.pureweather")) startActivity(packageManager.getLaunchIntentForPackage("hanjie.app.pureweather"))
            }
        }
    }

    override fun onInitViewsAndData() {
        startService(Intent(context, EventService::class.java))
        startService(Intent(context, SockectService::class.java))
        AnimUtil(text_now_dian).startAnim() //小数点

        if (V.mAppList.isNotEmpty()) {
            val adapter = MainAppListAdapter(V.mAppList)
            recycler_apps.adapter = adapter
            recycler_apps.layoutManager = GridLayoutManager(context, 5, GridLayoutManager.VERTICAL, false)
            adapter.onItemClickListener = this@MainActivity
            text_ad.setOnClickListener(this)
            text_now_time.setOnClickListener(this)
            text_mobile_name.setOnClickListener(this)
            showAd(V.mAdvert?.title + "")
        } else {
            MainEvent.post(MainEType.ShowToast, "商家未添加应用，请添加后重启设备！")
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        recycler_apps?.tag = position
        val item = adapter?.getItem(position) as Soft
        when (item.packageName) {
            "com.dangf.app.setting" -> MainEvent.post(MainEType.BrightnessAdjustmentWindows, this)
            "com.dangf.app.clean" -> IOEvent.post(IOEType.CleanGameData)
            "com.dangf.app.suoping" -> MainEvent.post(MainEType.OutboardMotorWindows, this)
            else -> {
                try {
                    startActivity(packageManager.getLaunchIntentForPackage(item.packageName))
                } catch (e: Exception) {
                    if (view?.findViewById<CircleProgressView>(R.id.circle_progress)?.visibility != View.VISIBLE) {
                        AlertDialog.Builder(this).setTitle("提示").setMessage("此应用尚未安装，是否现在进行安装?").setNegativeButton("取消", null)
                                .setPositiveButton("安装", { _, _ -> downSoft(item, view!!) }).show()
                    }
                }
            }
        }
    }


    //时间更新
    fun updateTimeInfo(delayed: Long = 0) {
        layout_now_time.postDelayed({
            text_now_time.text = DateUtils.getStrTime(" HH mm ")
            val ss = (60 - DateUtils.getStrTime("ss").toInt()) * 1000
            if (text_now_time.text == " 00 00 ") updateDateInfo()
            updateTimeInfo(ss.toLong())
        }, delayed)
    }

    //更新日期
    fun updateDateInfo() {
        val calendar = Calendar.getInstance()
        calendar.time = Date(System.currentTimeMillis())

        text_now_date_info.text = DateUtils.getStrTime("yyyy年MM月dd日　EEEE　") + CalendarUtil.getCurrentDay(calendar)
    }

    //显示公告
    fun showAd(text: String) {
        var title = text
        while (title.length < 36) {
            title = "$title　　　　$text"
        }

        text_ad.text = "　$title"
    }

    fun downSoft(item: Soft, view: View) {
        view.findViewById<SlantedTextView>(R.id.slanted_text_tag).text = "请求中"
        val request = NoHttp.createDownloadRequest(V.HTTP_FILE_URL + item.apkUrl, getExternalFilesDir("hais").toString(), "${item.name}.apk", true, true)
        NoHttp.getDownloadQueueInstance().add(0, request, object : DownloadListener {
            override fun onFinish(what: Int, filePath: String?) {
                view.findViewById<SlantedTextView>(R.id.slanted_text_tag).text = "安装中"
                item.apkUrl = filePath + ""
                var map = mapOf<String, Any>(Pair("View", recycler_apps), Pair("Data", item))
                IOEvent.post(IOEType.InstallApk, map)
            }

            override fun onDownloadError(what: Int, exception: java.lang.Exception?) {
                view.findViewById<SlantedTextView>(R.id.slanted_text_tag).text = "已出错"
                view.findViewById<CircleProgressView>(R.id.circle_progress).visibility = View.GONE
            }

            override fun onCancel(what: Int) {
                view.findViewById<SlantedTextView>(R.id.slanted_text_tag).text = "已取消"
            }

            override fun onProgress(what: Int, progress: Int, fileCount: Long, speed: Long) {
                view.findViewById<CircleProgressView>(R.id.circle_progress).progress = progress
            }

            override fun onStart(what: Int, isResume: Boolean, rangeSize: Long, responseHeaders: Headers?, allCount: Long) {
                view.findViewById<CircleProgressView>(R.id.circle_progress).visibility = View.VISIBLE
                view.findViewById<SlantedTextView>(R.id.slanted_text_tag).text = "下载中"
            }

        })
    }

    override fun onResume() {
        super.onResume()
        updateTimeInfo()
        updateDateInfo()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) true else super.onKeyDown(keyCode, event)
    }
}


